/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bff.spi.action.datamapping;

import com.inspur.edp.bff.api.dataprocessor.IDataConvertor;
import com.inspur.edp.bff.api.exception.BffFrameworkException;
import com.inspur.edp.bff.api.exception.ErrorCodes;
import com.inspur.edp.bff.api.manager.SourceConfig;
import com.inspur.edp.bff.api.manager.context.DataMapperContext;
import com.inspur.edp.bff.spi.builtin.BffModelResInfoImpl;
import com.inspur.edp.bff.spi.utils.BffActionNames;
import com.inspur.edp.cef.api.changeListener.EntityDataChangeListener;
import com.inspur.edp.cef.api.dataType.entity.ICefRootEntity;
import com.inspur.edp.cef.entity.accessor.entity.IEntityAccessor;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.spi.entity.resourceInfo.ModelResInfo;
import com.inspur.edp.udt.entity.IUdtData;
import lombok.var;

import java.util.ArrayList;
import java.util.Map;

public class DefaultDataMappingAction extends DataMappingAction {

    public DefaultDataMappingAction(DataMapperContext context) {
        super(context);
    }

    @Override
    protected void execute() {
        ArrayList<SourceConfig> sourceConfigs = getContext().getSourceConfigs();
        if (sourceConfigs == null || sourceConfigs.size() == 0) {
            throw new BffFrameworkException(ErrorCodes.BFF_FRAMEWORK_2029);
        }
        java.util.ArrayList<IEntityData> vmDatas = new java.util.ArrayList<IEntityData>();

        IDataConvertor dataConvertor = getContext().getDataConvertor();
        if (!getMapContext().getSourceData().containsKey(BffActionNames.DefaultName)) {
            return;
        }

        for (IEntityData entityData : getMapContext().getSourceData().get(BffActionNames.DefaultName)) {
            if (entityData == null) {
                vmDatas.add(null);
                continue;
            }
            Object tempVar = getContext().getBffManager().createData();

            IEntityAccessor vmAccessor = (IEntityAccessor) ((tempVar instanceof IEntityAccessor) ? tempVar : null);

            IEntityData voData = (IEntityData) ((vmAccessor.getInnerData() instanceof IEntityData) ? vmAccessor.getInnerData() : null);

            //TODO Accessor暂不支持复杂类型赋值，临时用data赋值，在传给Accessor的方式处理
            dataConvertor.convertFromBEData(entityData, voData);

            //region 扩展
            dealExtendMapping(voData, entityData);


            vmAccessor.setInnerData(voData);

            if (!(getMelInfo() instanceof BffModelResInfoImpl)) {
                if (getMapContext().getIsNew()) {
                    dealDefaultValue(vmAccessor);
                }
            }

            //TODO 临时先返回InnerData，目前Accessor的ID不能序列化，等后续支持自定义序列化后，传Accessor
            vmDatas.add((IEntityData) ((vmAccessor.getInnerData() instanceof IEntityData) ? vmAccessor.getInnerData() : null));
        }

        getMapContext().setTargetResult(vmDatas);
    }

    private void dealExtendMapping(IEntityData voData, IEntityData beData) {
        var extList = getContext().getExtList();
        if (extList == null || extList.size() < 1)
            return;
        for (var ext : extList) {
            ext.mapData2Vo(voData, beData);
        }
    }

    private ModelResInfo getMelInfo() {
        return this.getContext().getModelResourceInfo();
    }

    private void dealDefaultValue(IEntityData vmAccessor) {
        IEntityData voData = (IEntityData) ((((IEntityAccessor) vmAccessor).getInnerData() instanceof IEntityData) ? ((IEntityAccessor) vmAccessor).getInnerData() : null);
        EntityDataChangeListener listener = EntityDataChangeListener.createInstance();
        listener.registListener(vmAccessor);
        ICefRootEntity entinty = getContext().getBffManager().createEntity(vmAccessor.getID());
        entinty.assignDefaultValue(vmAccessor);
        if (getMapContext().getVoDefaultValue() != null && getMapContext().getVoDefaultValue().getDefaultValue() != null && getMapContext().getVoDefaultValue().getDefaultValue().size() > 0) {
            for (Map.Entry<String, Object> defaultItem : getMapContext().getVoDefaultValue().getDefaultValue().entrySet()) {
                Object value = defaultItem.getValue();
                //不支持直接setUdt,新增时传参的方式赋udt默认值
                if (value instanceof IUdtData)
                    continue;
                vmAccessor.setValue(defaultItem.getKey(), defaultItem.getValue());
            }
        }

        IChangeDetail defalutChange = listener.getChange();
        if (defalutChange != null) {
            getContext().getBffManager().modify(defalutChange);
        }
    }
}
